package com.appspot.chooserepository.server;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;

public class DataStoreUtils {
	
	public static void storeRepositoryUserData(RepositoryUserData repositoryUserData) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.makePersistent(repositoryUserData);
		} catch (Exception e) {
			
		} 
		pm.close();
	}

	@SuppressWarnings("unchecked")
	public static List<RepositoryUserData> queryRepositoriesUserData() {
		List<RepositoryUserData> repositoriesUserDataList = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {			
			String query = "select from " + RepositoryUserData.class.getName();
			repositoriesUserDataList = (List<RepositoryUserData>) pm.newQuery(query).execute();
		} catch (Exception e) {
			
		}
		ArrayList<RepositoryUserData> result = new ArrayList<RepositoryUserData>(repositoriesUserDataList);
		pm.close();
		return result;
	}
	
	public static void deleteRepositoriesUserData() {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {	
			pm.newQuery(RepositoryUserData.class).deletePersistentAll();
		} catch (Exception e) {
			
		} 
		pm.close();
	}
	
	public static void storeLastChangedDate(Date lastChangedDate) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		LastChangedDate presentLastChangedDate = queryLastChangedDate();
		if (presentLastChangedDate == null) {
			presentLastChangedDate = new LastChangedDate(lastChangedDate);
		} else {
			presentLastChangedDate.setLastChanged(lastChangedDate);
		}
		try {
			pm.makePersistent(presentLastChangedDate);
		} finally {
			pm.close();
		}
	}
	
	@SuppressWarnings("unchecked")
	public static LastChangedDate queryLastChangedDate() {
		LastChangedDate lastChangedDate = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {			
			String query = "select from " + LastChangedDate.class.getName();
			List<LastChangedDate> lastChangedDateList = (List<LastChangedDate>) pm.newQuery(query).execute();
			if (lastChangedDateList.size()>0)
				lastChangedDate = lastChangedDateList.get(0);
		} catch (Exception e) {
			
		}
		pm.close();
		return lastChangedDate;
	}

}
